package com.example.zjsr.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.zjsr.common.Key;
import com.example.zjsr.common.ServerResponse;

import com.example.zjsr.common.Uploader;
import com.example.zjsr.controller.U3DRobotController;
import com.example.zjsr.pojo.*;
import com.example.zjsr.pojo.ilabresult.IlabSport;
import com.example.zjsr.service.U3DRobotService;

import com.example.zjsr.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;


@Service
public class U3DRobotServiceImpl implements U3DRobotService {

    private static final Logger logger = LoggerFactory.getLogger(U3DRobotServiceImpl.class);

    @Autowired
    public RedisUtil redisUtil;


    public static final String FILE_PREFIX = "E:\\tempfile2\\";

    public static final Long CHUNK_SIZE = 1048576L;

//    public static final String FILE_UPLOAD = "http://www.ilab-x.com/project/log/attachment/upload";

    //测试地址和正式地址 http://202.205.145.156:8017->http://www.ilab-x.com
    public final String FILE_UPLOAD = "http://www.ilab-x.com/open/api/v2/attachment_upload?";

    /**
     * 提交实验成绩
     * @param commerce
     * @return
     */
    @Override
    public ServerResponse<String> addScore(String accessToken,Commerce commerce){
        String accessToken2 = "";
        try{
            accessToken2 = URLEncoder.encode(accessToken,"UTF-8");
        }catch (Exception e){
            System.out.println("accessToken获取失败");
            return ServerResponse.createByErrorMsg("上传失败");
        }
        /**
         * 提交给ilab成绩
         */
        IlabSport ilabSport = commerce.getIlabSport();
        String originId=UUID.randomUUID().toString().replaceAll("-","_");
        ilabSport.setOriginId(originId);
        ilabSport.setAppid((int)Key.issuerId);
        // 项目名称
        ilabSport.setTitle("跨境电商保税进口虚拟仿真实验");

        System.out.println(ilabSport);
        /**
         * 生成实验报告
         */
        // 实验得分
        double score = commerce.getExperimentScore();
        //实验结束时间
        long  startDate= commerce.getExperimentStartDate().getTime();
        //实验开始时间
        //根据实验记录id查询试验记录主表
        long endDate = commerce.getExperimentEndDate().getTime();
        //实验用时
        int timeUsed = (int) (endDate - startDate) / 1000;
        ExpRes expRes=new ExpRes();
        expRes.setStartDate(startDate);
        expRes.setEndDate(endDate);
        expRes.setUsername(commerce.getUsername());
        expRes.setTimeUsed(timeUsed);
        expRes.setExperimentSuggest(commerce.getExperimentSuggest());
        expRes.setScore(score);
        HashMap<String,Double> reportDetail=new HashMap<>();
        reportDetail.put("备案登记",commerce.getPutRecordsScore());
        reportDetail.put("海关注册编码",commerce.getRegistrationCodeScore());
        reportDetail.put("电子口岸IC卡",commerce.getElectronicPortIcScore());
        reportDetail.put("单一窗口注册备案",commerce.getSingleWindowScore());
        reportDetail.put("电子口岸数据中心企业注册",commerce.getElectronicPortScore());
        reportDetail.put("商品备案",commerce.getGoodsRecordScore());
        reportDetail.put("账册申请、申报",commerce.getBooksDeclareScore());
        reportDetail.put("货物运抵",commerce.getGoodsArrivedScore());
        reportDetail.put("报关、报检预录入",commerce.getCustomsEntryScore());
        reportDetail.put("过卡进区",commerce.getCardAreaScore());
        reportDetail.put("查验、报关",commerce.getCheckScore());
        reportDetail.put("表单申报",commerce.getDeclarationFormScore());
        reportDetail.put("商品出库拣货",commerce.getGoodsPickedScore());
        reportDetail.put("尾程派送",commerce.getSendScore());
        reportDetail.put("合计分数",commerce.getTotalPoints());
        reportDetail.put("前期准备",commerce.getPrepareScore());
        reportDetail.put("入区准备",commerce.getAreaPrepareScore());
        reportDetail.put("入区通关",commerce.getInCustomsScore());
        reportDetail.put("出区通关",commerce.getOutCustomsScore());
        reportDetail.put("尾程派送总分",commerce.getGoodsPickedAllScore());
        String issuerId = String.valueOf(Key.issuerId);

        /**
         * 提交成绩
         */
        String json= JSONObject.toJSONString(ilabSport);
        System.out.println("json="+json);
        logger.info("AccessToken{}",accessToken2);
        try {
            String code= PostUtil.post(accessToken2,json,"application/json");
            System.out.println("调用实验结果接口的返回码==================" + code);
            JSONObject jsonObject= JSON.parseObject(code);
            if(jsonObject.getInteger("code")==0){
                String filename=System.currentTimeMillis()+".xlsx";
                String filePath ="E:\\tempfile2\\"+filename;
                ExcelParser.createExcel(filePath,reportDetail,expRes);
                filename=URLEncoder.encode(filename);
                String title="文件标题";
                title=URLEncoder.encode(title);
                String remarks = URLEncoder.encode(String.valueOf(System.currentTimeMillis()));
                String pdfFileName=System.currentTimeMillis()+".pdf";
                String pdfFilePath="E:\\tempfile2\\"+pdfFileName;
                String upload = FILE_UPLOAD + "access_token="+accessToken2+"&appid="+Integer.valueOf(issuerId)+"&originId="+originId+"&filename="+pdfFileName+"&title="+title+"&remarks="+remarks;
                logger.info("FILE_UPLOAD={}",upload);
                PostUtilInto.excelToPdf(filePath,pdfFilePath);
                String res=PostUtilInto.formUpload(upload,pdfFilePath,pdfFileName);
                logger.info("res={}",res);
                if(res.equals("200")){
                    return ServerResponse.createBySuccessMsg("数据插入成功！");
                }else{
                    return ServerResponse.createByErrorMsg("数据插入失败！");
                }
            }else{
                return ServerResponse.createByErrorMsg("数据插入失败！");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("数据插入失败！");
        }
    };

}
